<template>
	<SkeletonScreen v-if="loading"></SkeletonScreen>
	<view class="container">
		<!-- 用户信息部分 -->
		<view class="user-info">
			<text class="username">小程序用户 {{users.openId}}</text>
			<text class="expire-info">SVIP会员：{{timeStatus}} 到期，购后有效期将延长</text>
		</view>

		<!-- 分割线 -->
		<view class="divider"></view>

		<!-- 会员类型标题 -->
		<view class="section-title">
			<text>VIP会员</text>
			<text class="subtitle">手机/平板/电脑均可使用</text>
		</view>

		<!-- 会员选项 -->
		<view class="membership-options">

			<!-- 连续包年选项 -->
			<view class="option-card" v-for="(item , index ) in coinAlpayValue"
				:class="{ 'active': selectedOption === index }" @click="selectOption(index)">
				<view class="option-header">
					<text class="option-title">查好人生·开播特惠</text>
					<text class="option-type">{{item.name}}</text>
				</view>
				<view class="option-price">
					<text class="current-price">¥{{item?.currentPrice}}</text>
					<text class="original-price">¥{{item?.originalPrice}}</text>
				</view>
				<view class="corner-tag" v-if="selectedOption === index">省¥&nbsp;{{discountAmount}}</view>
			</view>

		</view>

		<!-- 会员权限提示 -->
		<view class="privileges-section">
			<view class="section-header">
				<text class="title">会员特权</text>
				<text class="subtitle">开通即享以下所有权益</text>
			</view>

			<view class="privileges-grid">
				<view class="privilege-item" v-for="item in privileges" :key="item.id">
					<image class="privilege-icon" :src="item.icon" mode="aspectFit"></image>
					<text class="privilege-text">{{ item.text }}</text>
				</view>
			</view>
		</view>

		<!-- 底部支付按钮 -->
		<view class="payment-footer">
			<view class="price-info">
				<text>确认协议并支付</text>
				<text class="price">¥{{ currentPrice.coinAlpayValue }}</text>
			</view>
			<text class="discount-info">已减¥{{ discountAmount }}</text>
			<navigator url="/pages/alpay/content/content" class="agreement-text">开通前请阅读《小程序系列会员服务协议》</navigator>
			<button class="payment-button" @click="handlePayment">立即支付</button>
		</view>

	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue';
	import {
		coinAlpay
	} from '@/API/alpayApis.js';
	const loading = ref(true)
	const coinAlpayValue = ref([]); //金额

	const users = ref([]);
	const timeStatus = ref();

	// 当前选中的选项
	const selectedOption = ref(0);

	// 会员金额
	const coinAlpayFunction = async () => {
		let res = await coinAlpay();
		coinAlpayValue.value = res.data;
		console.log("金额：", res.data);
		// #ifdef MP-WEIXIN
		let user = uni.getStorageSync("user");
		users.value = user;
		timeStatus.value = formatTimestamp(user.statusCreate);
		// #endif
		loading.value = false
	}
	// 会员金额
	coinAlpayFunction();
	// 时间码转换
	function formatTimestamp(timestamp) {
		const date = new Date(timestamp);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
		const day = String(date.getDate()).padStart(2, '0');
		const hour = String(date.getHours()).padStart(2, '0');
		const minute = String(date.getMinutes()).padStart(2, '0');

		return `${year}-${month}-${day} ${hour}:${minute}`;
	}


	// 会员特权数据
	const privileges = ref([{
			id: 1,
			text: '免广告特权',
			icon: '/static/coin_icon/mian.png'
		},
		{
			id: 2,
			text: '高清画质',
			icon: '/static/coin_icon/gao.png'
		},
		{
			id: 3,
			text: '无观看限制',
			icon: '/static/coin_icon/camera.png'
		},
		{
			id: 4,
			text: '会员专属内容',
			icon: '/static/coin_icon/hui.png'
		},
		{
			id: 5,
			text: '多设备使用',
			icon: '/static/coin_icon/duo.png'
		},
		{
			id: 6,
			text: '提前观看',
			icon: '/static/coin_icon/eye.png'
		},
	])

	// 计算当前价格
	const currentPrice = computed(() => {
		const coin = [];
		coin.coinAlpayValue = coinAlpayValue?.value[selectedOption.value]?.currentPrice;
		coin.coinDays = coinAlpayValue?.value[selectedOption.value]?.days;
		return coin;
	})

	// 计算折扣金额
	const discountAmount = computed(() => {
		const option = coinAlpayValue?.value[selectedOption.value];
		return option?.originalPrice - option?.currentPrice;
	})

	// 选择会员选项
	const selectOption = (option) => {
		selectedOption.value = option;
		uni.pageScrollTo({
			scrollTop: 500,
			duration: 800
		})
	}

	// 处理支付
	const handlePayment = () => {
		uni.showToast({
			title: `支付¥${currentPrice.value.coinAlpayValue}`,
			icon: 'none'
		})
		// 这里可以添加实际的支付逻辑
		// #ifdef MP-WEIXIN
		let user = uni.getStorageSync("user");
		let days = currentPrice.value.coinDays;
		let coinAlpayValue = currentPrice.value.coinAlpayValue;
		// let totalFee = 
		console.log("天数{},价格{}：", days, coinAlpayValue);
		requestPayment(coinAlpayValue, days, user.openId, user.id);


		// #endif
	}


	// 微信支付
	function requestPayment(totalFee, days, openId, UserId) {
		// 获取支付参数
		uni.request({
			url: 'https://min.erkantv.cn:8443/unifiedOrder',
			method: 'POST',
			data: {
				body: '商品描述',
				outTradeNo: 'outTradone' + new Date().getTime(),
				totalFee: totalFee * 100, // 总金额，单位为分
				spbillCreateIp: '用户IP',
				openid: openId
			},
			success(res) {
				if (res.data) {
					// 调起微信支付
					uni.requestPayment({
						timeStamp: res.data.timeStamp,
						nonceStr: res.data.nonceStr,
						package: 'prepay_id=' + res.data.prepayId,
						signType: 'MD5',
						paySign: res.data.paySign,
						success(res) {
							console.log('支付成功', res);
							console.log("days", days)
							let now = new Date();
							// 创建一个新的日期对象，增加一n天
							let oneDayLater = new Date(now);
							oneDayLater.setDate(now.getDate() + days);
							console.log("time个天后的时间戳是：" + oneDayLater.getTime());
							uni.request({
								url: 'https://min.erkantv.cn:8443/portal/openId/updateStatus',
								method: 'GET',
								data: {
									id: UserId,
									status: 1,
									statusCreate: oneDayLater.getTime()
								},
								success: (e) => {
									uni.showLoading({
										title: '数据更新中...',
									})
									console.log("会员开通成功!");
									setTimeout(() => {
										uni.hideLoading();
										uni.showToast({
											title: '数据更新成功！',
											icon: 'none'
										})
									}, 3000); // 延迟 2000 毫秒
								}
							})
							uni.showToast({
								title: '支付成功！',
								icon: 'none'
							})
							getOpenId();
							const shareUserId = uni.getStorageSync('ShareUserId')
							if (shareUserId > 0) {
								uni.request({
									url: 'https://min.erkantv.cn:8443/portal/openId/money',
									method: 'GET',
									data: {
							
										userId: shareUserId,
										money: totalFee / 2,
										close: true
									},
									success: (e) => {
										console.log("给推荐用户分红成功！")
										uni.removeStorageSync('ShareUserId')
									}
								})
							}
						},
						fail(res) {
							uni.showToast({
								title: '支付失败！',
								icon: 'none'
							})
							console.log('支付失败', res);
						}
					})
				}
			}
		});
	}
	function getOpenId(e) {
		const shareUserId = uni.getStorageSync('ShareUserId')
		uni.login({
			success(res) {
				if (res.code) {
					//发起网络请求
					uni.request({
						url: 'https://min.erkantv.cn:8443/portal/openId',
						method: "POST",
						header: {
							'content-type': 'application/json' // 默认值
						},
						data: {
							code: res.code,
							shareUserId: shareUserId
						},
						success: (rec) => {
							var user = rec.data;
							console.log('循环循环过来的', user);
							uni.removeStorageSync('user')
							uni.setStorageSync("user", user);
							// 问题持续时间
							//获取创建时间
							let createTime = new Date(user.statusCreate).getTime();
							// console.log("创建时间{}", createTime);
							//获取当前时间
							let now = new Date().getTime();
							// console.log("当前时间{}", now);
							//计算时间差
							let time = createTime - now;
							console.log("时间差{}", time);
							if (time < 0) {
								uni.request({
									url: 'https://min.erkantv.cn:8443/portal/openId/deleteStatus',
									method: "GET",
									header: {
										'content-type': 'application/json' // 默认值
									},
									data: {
										id: user.id,
										status: 0
									},
									success: (rec) => {
										console.log("会员身份变更!");
									}
								})
							}
	
						}
					})
				} else {
					console.log('登录失败！' + res.errMsg)
				}
			}
		})
	}
</script>

<style lang="scss">
	.container {
		padding: 20rpx 30rpx;
		background-color: #000;
		min-height: 100vh;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
	}

	.user-info {
		display: flex;
		flex-direction: column;
		padding: 20rpx 0;

		.username {
			font-size: 32rpx;
			color: #fff;
			font-weight: bold;
			padding-right: 20rpx;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}

		.expire-info {
			font-size: 26rpx;
			color: #888;
			margin-top: 10rpx;
		}
	}

	.divider {
		height: 1rpx;
		background-color: #333;
		margin: 20rpx 0;
	}

	.section-title {
		display: flex;
		flex-direction: column;
		margin-bottom: 30rpx;

		text {
			font-size: 34rpx;
			color: #fff;
			font-weight: bold;
		}

		.subtitle {
			font-size: 26rpx;
			color: #888;
			font-weight: normal;
			margin-top: 10rpx;
		}
	}

	.membership-options {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		flex: 1;
	}

	.option-card {
		background-color: #1d1d1d;
		border-radius: 16rpx;
		padding: 30rpx;
		position: relative;
		overflow: hidden;
		transition: all 0.3s ease;
		border: 2rpx solid #333;

		&.active {
			border-color: #ff0000;
			background-color: #1d1d1d;
			transform: translateY(-5rpx);
			box-shadow: 0 10rpx 20rpx rgba(255, 0, 0, 0.2);

			.option-type {
				color: #ff0000 !important;
			}
		}

		.option-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 20rpx;

			.option-title {
				font-size: 30rpx;
				color: #fff;
			}

			.option-type {
				font-size: 28rpx;
				color: #ff3333;
				font-weight: bold;
			}
		}

		.option-price {
			display: flex;
			align-items: flex-end;

			.current-price {
				font-size: 42rpx;
				color: #ff0000;
				font-weight: bold;
			}

			.original-price {
				font-size: 28rpx;
				color: #666;
				text-decoration: line-through;
				margin-left: 15rpx;
				margin-bottom: 4rpx;
			}
		}

		.corner-tag {
			position: absolute;
			right: 0;
			top: 0;
			background-color: #ff0000;
			color: #fff;
			font-size: 22rpx;
			padding: 6rpx 20rpx;
			border-bottom-left-radius: 16rpx;
			transform: translateY(-5rpx);
			animation: bounceIn 0.5s;
		}
	}

	/* 新增的会员特权区域样式 */
	.privileges-section {
		background-color: #1d1d1d;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-top: 40rpx;

		.section-header {
			display: flex;
			flex-direction: column;
			margin-bottom: 30rpx;

			.title {
				font-size: 32rpx;
				color: #fff;
				font-weight: bold;
			}

			.subtitle {
				font-size: 26rpx;
				color: #888;
				margin-top: 10rpx;
			}
		}

		.privileges-grid {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 30rpx;

			.privilege-item {
				display: flex;
				align-items: center;

				.privilege-icon {
					width: 40rpx;
					height: 40rpx;
					margin-right: 15rpx;
				}

				.privilege-text {
					font-size: 28rpx;
					color: #fff;
				}
			}
		}
	}

	.payment-footer {
		background-color: #1d1d1d;
		padding: 30rpx;
		border-radius: 16rpx;
		margin-top: 40rpx;
		box-shadow: 0 -5rpx 20rpx rgba(0, 0, 0, 0.3);


		.price-info {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 15rpx;

			text {
				font-size: 32rpx;
				color: #fff;
			}

			.price {
				font-size: 40rpx;
				color: #ff0000;
				font-weight: bold;
			}
		}

		.discount-info {
			display: block;
			font-size: 26rpx;
			color: #ff0000;
			text-align: right;
			margin-bottom: 30rpx;
		}

		.agreement-text {
			display: block;
			font-size: 24rpx;
			color: #ff0000;
			text-align: center;
			margin-bottom: 30rpx;
		}

		.payment-button {
			background-color: #ff0000;
			color: #fff;
			border-radius: 50rpx;
			height: 90rpx;
			line-height: 90rpx;
			font-size: 34rpx;
			font-weight: bold;
			transition: all 0.3s;

			&:active {
				opacity: 0.9;
				transform: scale(0.98);
				background-color: #cc0000;
			}
		}
	}

	@keyframes bounceIn {
		0% {
			opacity: 0;
			transform: scale(0.3) translateY(-5rpx);
		}

		50% {
			opacity: 1;
			transform: scale(1.05) translateY(-5rpx);
		}

		100% {
			transform: scale(1) translateY(-5rpx);
		}
	}
</style>